package com.idea.relax.crypto.core;

import org.springframework.core.BridgeMethodResolver;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.util.ClassUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * @author: 沉香
 * @date: 2023/3/19
 * @description:
 */
public class AnnotatedElementUtil {

	public static boolean isAnnotated(MethodParameter methodParameter, Class<? extends Annotation> annotationType) {
		Method method = methodParameter.getMethod();
		boolean isMethodAnnotated = AnnotatedElementUtils.isAnnotated(method, annotationType);
		if (isMethodAnnotated) {
			return true;
		}
		Class<?> targetClass = method.getDeclaringClass();
		return AnnotatedElementUtils.isAnnotated(targetClass, annotationType);
	}

	public static <A extends Annotation> A getAnnotation(MethodParameter parameter, Class<A> annotationType) {
		Method method = parameter.getMethod();
		Class<?> targetClass = method.getDeclaringClass();
		Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
		specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
		A annotation = AnnotatedElementUtils.findMergedAnnotation(specificMethod, annotationType);
		if (null == annotation) {
			annotation = AnnotatedElementUtils.findMergedAnnotation(specificMethod.getDeclaringClass(), annotationType);
		}
		return annotation;
	}


}
